package com.example.zhang;

import androidx.fragment.app.Fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class SecondFragment extends Fragment implements Runnable, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    ListView list;
    private ArrayList<HashMap<String, String>> listItems;
    private ArrayList<HashMap<String, String>>listItems_t;
    private final String TAG ="a";
    private  SimpleAdapter adapter;
    private String time = "";
    private FloatingActionButton fb;
    private int i =0;
    private SoundPool sp;//声明一个SoundPool


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        listItems = new ArrayList<HashMap<String, String>>();//用于存放当前页面获取的list
        listItems_t = new ArrayList<HashMap<String, String>>();//用于存放收藏的items

        Thread t = new Thread((Runnable) this);//开启后会启动子线程中的run方法.
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        View view = inflater.inflate(R.layout.activity_second_fragment,null);
        list = (ListView)view.findViewById(R.id.li);
        adapter = new SimpleAdapter(getActivity(),listItems,R.layout.list_item,
                new String []{"ItemTitle","ItemDetail"},new int[]{R.id.textView3,R.id.textView4});
        list.setAdapter(adapter);//为当前页面listview设置adapter
        list.setOnItemClickListener(this);
        list.setOnItemLongClickListener(this);
        return view;
    }

    public void onActivityCreated(Bundle savedInstancesState){
        super.onActivityCreated(savedInstancesState);
        fb = getActivity().findViewById(R.id.floatingActionButton2);//切换背景按钮
        fb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             switch (i){
                 case 0 :list.setBackgroundResource(R.drawable.bg_2);i++;break;
                 case 1 :list.setBackgroundResource(R.drawable.bg_3);i++;break;
                 case 2 :list.setBackgroundResource(R.drawable.bg_4);i++;break;
                 case 3 :list.setBackgroundResource(R.drawable.bg_1);i++;break;
             }
             if(i>3)
                 i=0;
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView title = (TextView) view.findViewById(R.id.textView3);
        String words1 = String.valueOf(title.getText());
        Cutwords ct =new Cutwords();
        ct.Cutwords(words1);

    }

    public boolean onItemLongClick(AdapterView<?> parent, View view, int position,long id){
        Log.i(TAG, "In onItemLongClick...");
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("提示")
                .setMessage("请确认是否加入收藏")
                .setNegativeButton("否",null)
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {         //长按加入收藏
                        TextView word1 = (TextView) view.findViewById(R.id.textView3);
                        TextView word2 = (TextView) view.findViewById(R.id.textView4);
                        String words1 = String.valueOf(word1.getText());
                        String words2 = String.valueOf(word2.getText());
                        HashMap<String, String> map1 = new HashMap<String, String>();
                        map1.put("ItemTitle", words1);
                        map1.put("ItemDetail", words2);
                        listItems_t.add(map1);

                        DBManager db =new DBManager(getActivity());
                        db.add(listItems_t); // 将结果放入数据库中以便取出;
                        listItems_t.clear(); // 清空当前Arraylist内容；
                        Log.i(TAG, "from onItemLongClick  "+words2);
                    }
                });
        builder.create().show();
        return true;
    }
    public void run(){
        Log.i(TAG, "from run ...");
        SharedPreferences sharedPreferences =getActivity().getSharedPreferences("TIME", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(getActivity());
        time = sharedPreferences.getString("time_save","123");//获取app内存储的时间
        Date date = new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");//获取当前系统时间
        try {
            if(time.equals("2123")){
                Log.i(TAG, "今天已经更新过了！！！" + "程序更新时间是：" + time);
                DBManager db =new DBManager(getActivity());
                listItems=db.listAll();
            }
            else {
                String uu[] = {"181", "181_2","181_3","181_4"};//爬取网页前2页的单词
                for (String i : uu) {
                    Document doc = Jsoup.connect("http://www.yywords.com/Article/200803/" + i + ".html").get();

                    Element dc = doc.select("#fontzoom").first();//单词
                    Elements wq = dc.getElementsByTag("p");
                    for (Element we : wq) {
                        Elements wr = we.getElementsByTag("span");
                        Elements wt = we.getElementsByTag("b");
                        if (wr.size() > 0 && wt.size() > 0 && !wr.text().isEmpty() && !wt.text().isEmpty() && !we.text().matches("[\\p{Upper}]")) {
                            HashMap<String, String> map1 = new HashMap<String, String>();
                            Cutwords ct =new Cutwords();
                            ct.Cutwords(we.text());
                            map1.put("ItemTitle", ct.Cut());
                            map1.put("ItemDetail", ct.Cut_b());
                            listItems.add(map1);
                        }
                    }
                }
                DBManager db = new DBManager(getActivity());
                db.deleteAll();
                Log.i("db", "删除所有记录");
                db.addAll(listItems);
                Log.i("db", "添加新记录集");
                @SuppressLint("WrongConstant") SharedPreferences sp = getActivity().getSharedPreferences("TIME",Context.MODE_APPEND);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("time_save", format.format(date));
                editor.apply();
                Log.i(TAG, "完成每日更新" + format.format(date));
            }


        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}